import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class FlowViewModel : ViewModel() {
    private val input = MutableStateFlow("")
    val titleStateFlow: StateFlow<String> = input

    fun onNameChange(msg: String) {
        input.value = msg
    }
}

@Composable
fun FlowExample(viewModel: FlowViewModel = FlowViewModel()) {
    val title by viewModel.titleStateFlow.collectAsState()
    TextField(
        title,
        supportingText = {
            Text(text = title)
        },
        onValueChange = { viewModel.onNameChange(it) },
        modifier = Modifier.padding(20.dp)
    )
}


class LiveDataViewModel : ViewModel() {
    private val input = MutableStateFlow("")
    val titleStateFlow: StateFlow<String> = input
    //接收输入框传进来的内容
    fun onTitleChange(msg: String) {
        //告诉MutableLiveData数据发生了改变
        input.value = msg
    }
}

//@Composable
//fun LiveDataDemo(viewModel: LiveDataViewModel = viewModel()) {
//    val title by viewModel.titleStateFlow.collectAsState()
//    TextField(title) {
//        //传出输入的内容
//        viewModel.onTitleChange(it)